import React, { useEffect, useState } from 'react';
import { Modal, Form, Row, Col, Input, TreeSelect, InputNumber, message } from 'antd';
import { FormInstance } from 'antd/es/form/Form';
import ASelect, { ASelectOptionType } from '@/components/SelfComp/ASelect';
import { ApiItem, ApiSelectTreeItem } from '@/types/api';
import { DataItem, FlagEnum, FormModalProps } from '@/types/global';
import { formLayout, modalFormItemLayout, maxModalFormItemLayout } from '@/utils/commons';

type UpdateApiProps<T> = FormModalProps<T> & {
  flag: FlagEnum;
  apiTypeData: DataItem[];
  apiTreeData: ApiSelectTreeItem[];
}

const FormItem = Form.Item;

const UpdateApiModal: React.FC<UpdateApiProps<ApiItem>> = (props) => {
  /** 接口url栏位是否可见，true-显示，false-不显示 */
  let [apiUrlVisible, setApiUrlVisible] = useState<boolean>(false);
  const formRef = React.createRef<FormInstance>();

  useEffect(() => {
    const { formData } = props;
    const { apiType } = formData;
    if (apiType === '2' || apiType === '4') {
      setApiUrlVisible(true);
    } else {
      setApiUrlVisible(false);
    }
  }, []);

  const onOk = () => {
    const { formData, flag } = props;
    if (flag === 'view') {
      const { onHandlerOK } = props;
      if (onHandlerOK) {
        onHandlerOK(formData);
      }
    } else {
      const { apiId } = formData;
      formRef.current!.validateFields().then(fieldsValue => {
        console.info(fieldsValue);
        const values = {
          ...fieldsValue,
          apiId
        };
        const { apiType } = values;
        if (apiType !== '4' && apiType !== '2') {
          message.warn('只允许修改接口/按钮权限，请重新选择');
          return;
        }
        console.log('Received values of form: ', values);
        const { onHandlerOK } = props;
        if (onHandlerOK) {
          onHandlerOK({
            ...values
          });
        }
      }).catch((err) => console.info('表单校验不通过'));
    }
  };

  const onCancel = () => {
    // 先清除form表单
    formRef.current!.resetFields();
    const {onHandlerCancel} = props;
    if (onHandlerCancel) {
      onHandlerCancel();
    }
  }

  /**
   * 菜单类型栏位改变事件
   * 默认情况下 onChange 里只能拿到 value
   */
  const apiTypeChange = (value: string, option: ASelectOptionType | ASelectOptionType[]) => {
    // 查询该功能码对应的交易信息
    // console.log('apiTypeChange');
    formRef.current!.resetFields([
      'apiUrl'
    ]);
    // 菜单类型为2-按钮时，显示按钮位置栏位
    if (value === '2' || value === '4') {
      setApiUrlVisible(true);
      return;
    }
    if (value === '1') {
      setApiUrlVisible(false);
    }
    
  }

  const { formData, colon, modalWidth, modalVisible, apiTypeData, apiTreeData, loading, flag } = props;
  const formItemLayout = modalFormItemLayout;
  const modalTitle = (flag === 'edit' ? '修改接口权限' : '查看接口权限信息');
  const disabled = (flag === 'edit' ? false : true);

  return (
    <Modal
      title={modalTitle}
      destroyOnClose
      maskClosable={false}
      width={modalWidth}
      open={modalVisible}
      confirmLoading={loading}
      onOk={onOk}
      onCancel={onCancel}>
      <Form layout={formLayout} ref={formRef}>
        <Row>
          <Col span={24}>
            <FormItem label="上级菜单" name='parentApiId' {...maxModalFormItemLayout} colon={colon}
              initialValue={formData.parentApiId}
            >
              <TreeSelect
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={apiTreeData}
                allowClear
                showSearch
                treeNodeFilterProp="title"
                placeholder="请选择"
                disabled={disabled}
              />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label="接口权限类型" name='apiType' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '接口权限类型必输' }
              ]}
              initialValue={formData.apiType}
            >
              <ASelect dataSource={apiTypeData} onChange={apiTypeChange} disabled={disabled} />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label="接口权限名称" name='apiName' {...formItemLayout} colon={colon}
              rules={[
                { max: 30, message: '接口权限名称最多允许输入30个字符' },
                { required: true, message: '菜接口权限名称必输' }
              ]}
              initialValue={formData.apiName}
            >
              <Input disabled={disabled} />
            </FormItem>
          </Col>
        </Row>
        {
          !apiUrlVisible ? null :
          <Row>
            <Col span={24}>
              <FormItem label="接口url" name='apiUrl' {...maxModalFormItemLayout} colon={colon}
                rules={[
                  { required: apiUrlVisible, message: '接口url必输' },
                  { max: 50, message: '接口url最多允许输入50个字符' }
                ]}
                initialValue={formData.apiUrl}
              >
                <Input disabled={disabled} />
              </FormItem>
            </Col>
          </Row>
        }
        <Row>
          <Col span={12}>
            <FormItem label="菜单图标" name='apiIcon' {...formItemLayout} colon={colon}
              initialValue={formData.apiIcon}
            >
              <Input disabled={disabled} />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label="接口权限编码" name='apiCode' {...formItemLayout} colon={colon}
              rules={[
                { max: 30, message: '接口权限编码最多允许输入30个字符' },
                { required: true, message: '接口权限编码必输' },
                { pattern: new RegExp(/^[A-Za-z][A-Za-z0-9-_:]{1,30}$/, "g"), message: '菜单编号只能以字母开头，由A-Za-z0-9组成，最大长度为30' }
              ]}
              initialValue={formData.apiCode}
            >
              <Input disabled={disabled} />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label="接口权限别名" name='apiAlias' {...formItemLayout} colon={colon}
              rules={[
                { max: 30, message: '接口权限别名最多允许输入30个字符' },
                { required: true, message: '接口权限别名必输' }
              ]}
              initialValue={formData.apiAlias}
            >
              <Input disabled={disabled} />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label="显示排序" name='apiSort' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '显示排序必输' }
              ]}
              initialValue={formData.apiSort}
            >
              <InputNumber min={0} style={{ width: '100%' }} disabled={disabled} />
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  );

}

export default UpdateApiModal